package com.itheima.utils;

import com.google.gson.Gson;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.*;

public class QiNiuYunUtils {
    private static String accessKey = "DrY3tqVfjFXB0qWMUnBS2aAg9UmZK5NEjQK-bv9A";
    private static String secretKey = "XUrkifwCaftX0s0pVuyiApf-mAmUnDS7QLba5DGP";
    private static String bucket = "itcast-health-cheng2";

    public static String upload2Qiniu(byte[] bytes, String fileName) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());
//...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        Response response = null;
        try {
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            response = uploadManager.put(bytes, fileName, upToken);
            try {
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
            ex.printStackTrace();
        }
        return "http://qns65jsuq.hn-bkt.clouddn.com/" + fileName;
    }

    public static String upload2Qiniu(String filePath, String fileName) {
        return "";
    }


    public static void deleteFileFromQiniu(String fileName) {
        Configuration cfg = new Configuration(Zone.zone2());
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth,cfg);
        String key = fileName;
        try {
            bucketManager.delete(bucket, key);
        } catch (QiniuException ex) {
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }
}
